package com.devcon5.StudentPlanner;

//Utilities map assignments to specific courses and grades

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.os.Bundle;

//In-project baseclasses and database adapter objects
import baseclasses.Assignment;
import database.AssignmentDAO;
import database.CourseDAO;
import database.GradeDAO;
import database.ReminderDAO;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ViewAssignments extends Activity {
	
//Basic views and adapters for populating views
	private ListView listview;
	private ArrayList<Assignment> assignments;
	private Context context = this;
	private TextView title;
	private AssignmentAdapter adapter;
	
//Variables for mapping actions and creating the menu when an Assignment is clicked, strings and integers
	private Map<String, Integer> actionMap;
	private static final String OPTION_VIEW_STRING = "View";
	private static final String OPTION_EDIT_STRING = "Edit";
	private static final String OPTION_DELETE_STRING = "Delete";
	private static final String OPTION_ADD_GRADE_STRING = "Add Grade";
	private static final String OPTION_ADD_REMINDER_STRING = "Set Reminder";
	private static final String OPTION_REMOVE_REMINDER_STRING = "Remove Reminder";
	private static final String OPTION_MARK_COMPLETE_STRING = "Mark As Completed";
	private static final String OPTION_MARK_INCOMPLETE_STRING = "Mark As Incomplete";	
	private static final int OPTION_VIEW = 69;
	private static final int OPTION_EDIT = 70;
	private static final int OPTION_DELETE = 71;
	private static final int OPTION_ADD_GRADE = 72;
	private static final int OPTION_ADD_REMINDER = 73;
	private static final int OPTION_REMOVE_REMINDER = 74;
	private static final int OPTION_MARK_COMPLETE = 75;
	private static final int OPTION_MARK_INCOMPLETE = 76;

	@Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.viewassignments);
        
    //Create the actionMap, mapping the option items to their view IDs
        createActionMap();
        
   //Initialize title and listview variables
  		title = (TextView)findViewById(R.id.viewassignments_title);
  		listview = (ListView)findViewById(R.id.viewassignments_listview);
  		
  	//populate array list with Assignments from database
		assignments = AssignmentDAO.getAssignmentsWithPreferences( context );
		adapter = new AssignmentAdapter( context, android.R.layout.simple_list_item_1, assignments );
		listview.setAdapter( adapter );
		title.setText( "Displaying " + assignments.size() + " assignment(s)" );
		
	//set onClickListener for list view items
		listview.setOnItemClickListener(new OnItemClickListener()
		{

			public void onItemClick(AdapterView<?> adapterView, View view, int index, long ID) 
			{
				final Assignment assignment = assignments.get(index);	//Which assignment was clicked
				final int newIndex = index;
				
				//display Edit or Delete menu onLongClick of assignment
				AlertDialog.Builder builder = new AlertDialog.Builder(context);
				builder.setTitle(assignment.getName());
				builder.setIcon(R.drawable.check);	//default Icon is the check icon
				
				final CharSequence menu[] = buildMenuItems(assignment);	//Create a menu of view/edit/delete options for grades/reminders for assignments
				
				builder.setItems(menu, new OnClickListener(){

					public void onClick(DialogInterface dialog, int which) {
						
						//Retrieve the menu ID matching the item clicked from the actionMap created earlier
						int action = actionMap.get(menu[which]);
						
						//Switch statement for action to take when a menu option is selected
						
						switch(action)
						{
						case OPTION_VIEW:	//if View option is clicked for Assignment, 
											//create AssignmentView object around this assignment
							
							Intent viewIntent = new Intent(context, AssignmentView.class);
							viewIntent.putExtra(Assignment.ASSIGNMENT_ID, assignment.getId());
							startActivity(viewIntent);
							return;
							
						case OPTION_EDIT:	//if Edit option is clicked, 
											//create EditAssignment object around this assignment
							
							Intent editIntent = new Intent( context, EditAssignment.class );
							editIntent.putExtra( Assignment.ASSIGNMENT_ID, assignment.getId() );
							startActivity(editIntent);
							return;
							
						case OPTION_DELETE:	//if Delete option is clicked, confirm and 
											//delete assignment from database
							
							AlertDialog.Builder builder2 = new AlertDialog.Builder(context);
							builder2.setTitle("Delete?");
							builder2.setIcon(android.R.drawable.ic_delete);
							builder2.setMessage("Are you sure you want to delete "+assignment.getName() +"?" +
									"\n\n(This will not affect any grades added for this assignment!)");
							builder2.setPositiveButton("Delete", new OnClickListener()
							{

								public void onClick(DialogInterface dialog,
										int which) {
									
									if (AssignmentDAO.deleteAssignment(context, assignment)<= 0)
									{
										Toast.makeText(context, "Error deleting assignment from database", Toast.LENGTH_LONG).show();
									}
									else
									{
										assignments.remove(newIndex);
										adapter.notifyDataSetChanged();
										title.setText("Displaying "+assignments.size()+" assignment(s)");
									}
								}
								
							});
							builder2.setNegativeButton("Cancel", null);
							AlertDialog alert = builder2.create();
							alert.show();
							return;
						
						case OPTION_ADD_GRADE:	//if AddGrade option, create AddGrade object around this assignment
							
							Intent addGrade = new Intent(context, AddGrade.class);
							addGrade.putExtra(Assignment.ASSIGNMENT_ID, assignment.getId());
							startActivity(addGrade);
							return;
							
						case OPTION_ADD_REMINDER:	//if AddReminder option, create EditAssignment object around this assignment
							
							Intent reminderIntent = new Intent(context, EditAssignment.class);
							reminderIntent.putExtra( Assignment.ASSIGNMENT_ID, assignment.getId() );
							reminderIntent.putExtra( EditAssignment.ADD_REMINDER, true );
							startActivity(reminderIntent);
							
							break;
							
						case OPTION_REMOVE_REMINDER:	//if RemoveReminder option, confirm & delete the reminder
							
							AlertDialog.Builder builder = new AlertDialog.Builder(context);
							builder.setTitle("Delete?");
							builder.setIcon(android.R.drawable.ic_delete);
							builder.setMessage("You really want to delete the reminder for this assignment?");
							builder.setPositiveButton("Delete", new OnClickListener() {

								public void onClick(DialogInterface dialog, int which) {
									ReminderDAO.deleteReminderByAssignment( context, assignment );
									adapter.notifyDataSetChanged();

								}
							});
							builder.setNegativeButton("Cancel", null);
							AlertDialog removeReminderAlert = builder.create();
							removeReminderAlert.show();

							break;
							
						case OPTION_MARK_COMPLETE:	//set the assignment mark to true, update the assignment in the DAO, & update list view

							assignment.setCompleted( true );
							AssignmentDAO.markAssigment( context, assignment );
							updateListView();
							break;

						case OPTION_MARK_INCOMPLETE:  //set the assignment mark to false, update the assignment in the DAO, & update list view

							assignment.setCompleted( false );
							AssignmentDAO.markAssigment(context, assignment);
							updateListView();
							break;

						default:
							break;
						
						}
						
					}
					
				});
				
				//Display the menu
				AlertDialog alert = builder.create();
				alert.show();
				
			}
			
		});
    }
	
	//On Activity Resume, update the listview
	@Override
	public void onResume()
	{
		super.onResume();
		updateListView();
	}
	
	/*
	 * Updates the list view by querying the db for all current assignments and setting the assignments array list.
	 * Also sets the AssignmentAdapter to a new adapter containing the updated array list & sets number of assignments displayed
	 */
	
	public void updateListView()
	{
		assignments = AssignmentDAO.getAssignmentsWithPreferences(context);
		adapter = new AssignmentAdapter(context, android.R.layout.simple_list_item_1, assignments);
		listview.setAdapter(adapter);
		title.setText( "Displaying "+assignments.size()+" assignment(s)" );
	}
	
	public boolean coursesExist()
	{
		if (CourseDAO.getCourses(context).size() > 0)
		{
			return true;
		}
		
		return false;
	}
	
	//Simple list view for assignments
	private class AssignmentAdapter extends ArrayAdapter<Assignment>
	{
		private ArrayList<Assignment> assignments;

		public AssignmentAdapter(Context context, int textViewResourceId, ArrayList<Assignment> assignments) {
			super(context, textViewResourceId, assignments);
			this.assignments = assignments;

		}
		
		//Create a view for assignment dynamically to accomodate longer assignment information
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.assignmentviewsimple, null);	//instantiate the simple assignment view
			}
			Assignment assignment = assignments.get(position);	//get the assignment that is selected from the arrayadapter that populates the list view
			if (assignment != null) {	//if the position isn't null, initialize variables for each view to the R.id files that correspond
				TextView assignmentName = (TextView) v.findViewById(R.id.assignmentviewsimple_name);
				TextView courseName = (TextView) v.findViewById(R.id.assignmentviewsimple_course);
				TextView dueDate = (TextView) v.findViewById(R.id.assignmentviewsimple_duedate);
				TextView description = (TextView) v.findViewById(R.id.assignmentviewsimple_description);
				ImageView completedIcon = (ImageView)v.findViewById( R.id.assignmentviewsimple_checkbox_icon);

				if ( assignmentName != null )
				{
					assignmentName.setText(assignment.getName());   
				}
				if( courseName != null )
				{
					courseName.setText(assignment.getCourseName(context));
				}
				if( description != null )
				{
					description.setText(assignment.getShortDescription());
				}
				if( dueDate != null )
				{
					dueDate.setText(assignment.getTimeUntilDueString());
				}
				if( completedIcon != null )
				{
					if( assignment.isCompleted() )
					{
						completedIcon.setVisibility( View.VISIBLE );
					}
					else
					{
						completedIcon.setVisibility( View.GONE );
					}
				}

			}
			return v;
		}				
	}
	
	public void createActionMap()
	{
		//Creates the actionMap by setting string values to corresponding integer ID values for onClick menu creation
		actionMap = new HashMap<String, Integer>();
		actionMap.put(OPTION_VIEW_STRING, OPTION_VIEW);
		actionMap.put(OPTION_EDIT_STRING, OPTION_EDIT);
		actionMap.put(OPTION_DELETE_STRING, OPTION_DELETE);
		actionMap.put(OPTION_ADD_GRADE_STRING, OPTION_ADD_GRADE);
		actionMap.put(OPTION_ADD_REMINDER_STRING, OPTION_ADD_REMINDER);
		actionMap.put(OPTION_REMOVE_REMINDER_STRING, OPTION_REMOVE_REMINDER);
		actionMap.put(OPTION_MARK_COMPLETE_STRING, OPTION_MARK_COMPLETE);
		actionMap.put(OPTION_MARK_INCOMPLETE_STRING, OPTION_MARK_INCOMPLETE);
	}
	
	//Creates a CharSequence array used for building Alert Dialog menus onItemClick in the listview.
	//It sets the correct menu option (i.e. If an assignment doesn't have a grade to show, don't show the Edit Grade Option--just the Add Grade option.
	public CharSequence[] buildMenuItems( Assignment assignment )
	{
		ArrayList<String> menuItems = new ArrayList<String>();
		menuItems.add( OPTION_VIEW_STRING );
		menuItems.add( OPTION_EDIT_STRING );
		menuItems.add( OPTION_DELETE_STRING );

		if( GradeDAO.getGradeByAssignmentId( context, assignment.getId()) == null )	//If no grades, add them
		{
			menuItems.add( OPTION_ADD_GRADE_STRING );
		}
		if( ReminderDAO.getReminderByAssignment( context, assignment ) == null) //If no reminders, add them
		{
			menuItems.add( OPTION_ADD_REMINDER_STRING );
		}
		else
		{
			menuItems.add( OPTION_REMOVE_REMINDER_STRING );
		}

		if( !assignment.isCompleted() )
		{
			menuItems.add( OPTION_MARK_COMPLETE_STRING );	//If the assignment isn't marked completed, give the option to do so
		}
		else
		{
			menuItems.add(OPTION_MARK_INCOMPLETE_STRING );	//Else, give the option to mark incomplete
		}

		return listToCharSequence( menuItems );

	}
	
	//Converts the ArrayList of Strings to a CharSequence to build the actual menu.
	public CharSequence[] listToCharSequence( List<String> list )
	{
		CharSequence[] charSequence = new CharSequence[ list.size() ];

		for( int i=0; i < list.size(); i++ )
		{
			charSequence[ i ] = list.get( i );
		}

		return charSequence;
	}
	
		//---------------------------------------------------------
		//
		//						MENU METHODS
		//
		//---------------------------------------------------------
		@Override
		public boolean onCreateOptionsMenu( Menu menu )
		{
			MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.viewassignmentsmenu, menu);	//Display the AddAssignment & Settings menu options
			return true;

		}

		//Handles the actions to take on selection of menu items
		@Override
		public boolean onOptionsItemSelected( MenuItem item )
		{

			switch ( item.getItemId() )
			{

			case R.id.addassignment:
				//If courses exist, create a new AddAssignment object; If no courses exist, display AddCourse Dialog
				if(coursesExist()){
					startActivity(new Intent(context, AddAssignment.class));
				}
				else
				{
					AlertDialog.Builder builder = new AlertDialog.Builder(context);
					builder.setTitle("No courses available!");
					builder.setMessage("You can't add assignments without courses to link them to!");
					builder.setPositiveButton("Add Course", new OnClickListener(){
						
						public void onClick(DialogInterface dialog, int which) {
							startActivity(new Intent(context, AddCourse.class));
						}
					});
					builder.setNegativeButton("Cancel", null);
					AlertDialog alert = builder.create();
					alert.show();
				}
				return true;

			case R.id.settings:	//Create a Preferences object to set settings

				Intent settingsIntent = new Intent( this, Preferences.class );
				startActivity( settingsIntent );

				break;

			}
			return false;
		}

	
	
}
